//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cn.intotw.rdcj.core.config.mybatis.dialect;



public class SQLServerDialect extends Dialect {
    public SQLServerDialect(String name) {
        super(name);
    }

    static String getOrderByPart(String sql) {
        String loweredString = sql.toLowerCase();
        int orderByIndex = loweredString.indexOf("order by");
        return orderByIndex != -1 ? sql.substring(orderByIndex) : "";
    }

    @Override
    protected String getPageSqlInner(String sql, int offset, int limit) {
        StringBuffer pagingBuilder = new StringBuffer();
        String orderby = getOrderByPart(sql);
        String distinctStr = "";
        String loweredString = sql.toLowerCase();
        String sqlPartString = sql;
        if (loweredString.trim().startsWith("select")) {
            int index = 6;
            if (loweredString.startsWith("select distinct")) {
                distinctStr = "DISTINCT ";
                index = 15;
            }

            sqlPartString = sql.substring(index);
        }

        pagingBuilder.append(sqlPartString);
        if (orderby == null || orderby.length() == 0) {
            orderby = "ORDER BY CURRENT_TIMESTAMP";
        }

        StringBuffer result = new StringBuffer();
        result.append("WITH query AS (SELECT ").append(distinctStr).append("TOP 100 PERCENT ").append(" ROW_NUMBER() OVER (").append(orderby).append(") as __row_number__, ").append(pagingBuilder).append(") SELECT * FROM query WHERE __row_number__ > " + offset * limit + " AND __row_number__ <= " + (offset + 1) * limit).append(" ORDER BY __row_number__");
        return result.toString();
    }
}
